package com.deluxelx.rmo.essay.domain.rule.engine;

import com.deluxelx.rmo.common.constants.TreeConstants;
import com.deluxelx.rmo.essay.domain.rule.logic.LogicFilter;
import com.deluxelx.rmo.essay.model.aggregates.TreeRuleRich;
import com.deluxelx.rmo.essay.model.bo.TreeNode;
import com.deluxelx.rmo.essay.model.bo.TreeRoot;
import com.deluxelx.rmo.essay.model.req.DecisionMakingReq;
import com.deluxelx.rmo.essay.model.res.DecisionMakingRes;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public abstract class EngineBase implements EngineConfig, EngineFilter {

    @Override
    public DecisionMakingRes process(DecisionMakingReq decisionMakingReq) {
        throw new RuntimeException("未实现规则引擎服务");
    }

    protected TreeNode engineDecisionMaker(TreeRuleRich treeRuleRich, DecisionMakingReq decisionMakingReq) {
        // 获取决策树根节点和 所有节点Map
        TreeRoot treeRoot = treeRuleRich.getTreeRoot();
        Map<Long, TreeNode> treeNodeMap = treeRuleRich.getTreeNodeMap();

        // 规则树根节点 ID
        Long rootNodeId = treeRoot.getTreeRootNodeId();
        // 得到根节点
        TreeNode treeNode = treeNodeMap.get(rootNodeId);

        // TODO （循环）过滤决策，找到最终的叶子节点（果实节点）
        // 节点类型【NodeType】：1.树茎、2.果实；如果不是果实节点则一直循环找
        while (!TreeConstants.FRUIT.equals(treeNode.getNodeType())) {
            String ruleKey = treeNode.getRuleKey();
            LogicFilter logicFilter = logicFilterMap.get(ruleKey);
            String decisionValue = logicFilter.getDecisionValue(decisionMakingReq);
            Long nextNodeId = logicFilter.decisionMaking(decisionValue, treeNode.getTreeNodeLineInfoList());
            treeNode = treeNodeMap.get(nextNodeId);
            log.info("决策树引擎 => {} userId：{} treeId：{} treeNode：{} ruleKey：{} matterValue：{}",
                    treeRoot.getTreeName(), decisionMakingReq.getUserId(), decisionMakingReq.getTreeId(),
                    treeNode.getTreeNodeId(), ruleKey, decisionValue);
        }
        return treeNode;
    }

}
